<template>
<div class="page">
  <div class="search">
    <a-form-model :form="form" :label-col="labelCol" :wrapper-col="wrapperCol" @submit.pre.prevent="search">
      <a-row type="flex" justify="center">
        <a-col :span="8">
          <a-form-model-item label="商户号：" prop="mcNo">
            <a-input v-model="form.mcNo" placeholder="请输入活动营销编号"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="活动状态" prop="mcStatus">
            <a-select v-model="form.mcStatus" placeholder="请选择活动状态">
              <a-select-option value="">请选择</a-select-option>
              <a-select-option value="0">草稿</a-select-option>
              <a-select-option value="1">未发布</a-select-option>
              <a-select-option value="2">进行中</a-select-option>
              <a-select-option value="3">已暂停</a-select-option>
              <a-select-option value="9">已结束</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="创建时间" prop="timeRange">
            <a-range-picker v-model="form.timeRange" :placeholder="['请选择创建开始时间','请选择创建结束时间']"></a-range-picker>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" style="text-align: center;">
          <a-space>
            <a-button type="primary" html-type="submit">查询</a-button>
            <a-button @click="reset">重置</a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-form-model>
  </div>
  <a-table :data-source="dataSource" :columns="columns" :pagination="pagination" row-key="mcNo" class="scrollable" :scroll="{x: true}" @change="pageChange">
    <template v-slot:operation="text, record">
      <div style="white-space: nowrap">
        <a-icon type="check-circle" theme="twoTone" twoToneColor="#4a9ff5" @click="publish(record)" title="发布" v-has-permission="['commissionRelease:edit']"></a-icon>
        <a-icon type="eye" theme="twoTone" twoToneColor="#4a9ff5" @click="view(record)" title="详情" v-has-permission="['commissionRelease:view']"></a-icon>
      </div>
    </template>
  </a-table>
  <commission-market-manager-operation ref="CommissionMarketManagerOperation" @refresh="fetch"></commission-market-manager-operation>
</div>
</template>

<script>
import CommissionMarketManagerOperation from './CommissionMarketManagerOperation'
import moment from 'moment'
export default {
  name: "commissionRelease",
  components: {CommissionMarketManagerOperation},
  data() {
    return {
      form: {
        mcNo: "",
        timeRange: [],
      },
      labelCol: {span:8},
      wrapperCol: {span: 16},
      dataSource: [],
      columns: [
        {title: '优惠活动名称', dataIndex: 'mcName'},
        {title: '营销活动编号', dataIndex: 'mcNo'},
        {title: '活动起始时间', dataIndex: 'mcStartDate'},
        {title: '活动终止时间', dataIndex: 'mcEndDate'},
        {
          title: '活动状态',
          dataIndex: 'mcStatus',
          customRender (text) {
            return ({
              "0": "草稿",
              "1": "未发布",
              "2": "进行中",
              "3": "已暂停",
              "4": "自然结束",
              "5": "强制结束",
              "6": "测试中",
              "9": "已结束",
            }[text]) || ''
          }
        },
        {
          title: '审核状态',
          dataIndex: 'auditStatus',
          customRender (text) {
            return ({
              "00": "待提交审批",
              "01": "新增-审批流程中",
              "02": "新增-审批通过",
              "03": "新增-审批拒绝",
              "11": "注销-审批流程中",
              "12": "注销-审批通过",
              "13": "注销-审批拒绝",
              "21": "停用-审批流程中",
              "22": "停用-审批通过",
              "23": "停用-审批拒绝",
              "31": "启用-审批流程中",
              "32": "启用-审批通过",
              "33": "启用-审批拒绝",
              "41": "修改-审批流程中",
              "42": "修改-审批通过",
              "43": "修改-审批拒绝",
              "51": "发布-审批流程中",
              "52": "发布-审批通过",
              "53": "发布-审批拒绝",
            }[text]) || ''
          }
        },
        {
          title: '营销方式',
          dataIndex: 'cashbackMethod',
          customRender (text) {
            return ({
              "0": "按交易金额比例返现",
              "1": "按交易金额固定返现",
            }[text]) || ''
          }
        },
        {title: '营销预算（元）', dataIndex: 'budget'},
        {title: '创建人', dataIndex: 'oprId'},
        {title: '创建时间', dataIndex: 'createTime'},
        {
          title: '操作',
          fixed: 'right',
          scopedSlots: {customRender: 'operation'}
        }
      ],
      pagination: {
        pageSizeOptions: ['5', '10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
    }
  },
  methods: {
    pageChange (e) {
      this.pagination.current = e.current;
      this.pagination.pageSize = e.pageSize;
      this.fetch();
    },
    search () {
      this.pagination = Object.assign({} ,{
        current: 1,
        pageSize: 10
      })
      this.fetch();
    },
    reset () {
      this.form = {
        mcNo: "",
        timeRange: [],
      };
      this.search();
    },
    async fetch () {
      let params = {
        mcNo: this.form.mcNo,
        pageNum: this.pagination.current,
        pageSize: this.pagination.pageSize
      };
      if (this.form.timeRange.length) {
        params.startTime = this.form.timeRange[0].format("YYYY-MM-DD HH:mm");
        params.endTime = this.form.timeRange[1].format("YYYY-MM-DD HH:mm");
      }
      const hideLoading = this.$message.loading("加载中...");
      try {
        const res = await this.$get('/admin/market/commissionRelease/list',
        )
        this.dataSource = res.data.records;
        this.$set(this.pagination, "total", +res.data.total);
        hideLoading()
      } catch (e) {
        hideLoading()
        this.$message.error('网络错误，请稍后再试！')
        console.error(e)
      }
    },
    async publish (record) {
      if(record.attendFlag=="1"){
        this.$message.error("上级行创建的活动没有权限操作");
        return;
      }
      if (record.mcStatus !== "1" && record.mcStatus !== "2") {
        this.$message.error("只能发布活动状态为未发布或进行中的活动");
        return;
      }
      if (record.auditStatus !== "51" && record.auditStatus !== "02" && record.auditStatus !== "42") {
        this.$message.error("只能发布已经审核通过未发布的活动");
        return;
      }
      const hideLoading = this.$message.loading("加载中...", 0);
      try {
          const res = await this.$get('/admin/market/commissionManager/view?flag=release&mcNo=' + record.mcNo)
        if (res.data.datailData) {
          this.$refs.CommissionMarketManagerOperation.show(this.resolveBeanInfo(res.data), 'release')
        } else {
          this.$message.error(res.data.message)
        }
      } catch (e) {
        this.$message.error('网络错误，请稍后再试！')
        console.error(e)
      }
      hideLoading()
    },
    resolveBeanInfo(data) {
        //详细页面标识
        const detailData = JSON.parse(data.datailData)
        const mcInfoObj = detailData.mcInfoObj;
        const orgInfoList = detailData.orgInfoList;
        const mchntInfoList = detailData.mchntInfoList;
        const productInfoList = detailData.productInfoList;
        const ruleInfoList = detailData.ruleInfoList;
        //优惠劵
        const flag=data.flag
        let beforeFlagView =false;
        let stockMchnt =true;
        let afterFlagView ='0';
        let newMchntFlagView =false;
        let postponeFlagView=false;
        let quantityLimit=null;
        let amountLimit=null;
        let feeLimit=null;
        //达标前手续费优惠规则
        if(mcInfoObj.beforeFlag==='1'){
            beforeFlagView=true
        }
        //存量商户达标条件
        if(mcInfoObj.stockMchntFlag==='0'){
            stockMchnt=false
        }
        //达标后手续费优惠规则
        if(mcInfoObj.afterFlag>0){
            afterFlagView='1'
        }
        //新增商户支持标志
        if(mcInfoObj.newMchntFlag>0){
            newMchntFlagView=true
        }
        ///新增商户周期顺延标志
        if (mcInfoObj.postponeFlag>0){
            postponeFlagView=true
        }
        //单个存量商户优惠交易笔数上限
        if(mcInfoObj.quantityLimit!=='0.00'){
            quantityLimit=mcInfoObj.quantityLimit
        }
        //单个存量商户优惠交易金额上限
        if(mcInfoObj.amountLimit!=='0.00'){
            amountLimit=mcInfoObj.amountLimit
        }
        //单个存量商户手续费优惠额上限
        if(mcInfoObj.feeLimit!=='0.00'){
            feeLimit=mcInfoObj.feeLimit
        }
        return {
            mcNo: data.mcNo, // 营销活动编号
            mcName: mcInfoObj.mcName, // 营销活动名称
            orgInfo: orgInfoList.map(i => i.orgId), // 参与机构
            mcDateRange: [moment(mcInfoObj.mcStartDate), moment(mcInfoObj.mcEndDate)], // 活动起始时间
            discountTransferMode: mcInfoObj.discountTransferMode, // 活动优惠方式
            budget: +mcInfoObj.budget, // 返现金额  数字格式 隐式转换
            merchantInfo: mchntInfoList.filter(i => i.mchntType === '0'), // 商户信息
            merchantCircleInfo: mchntInfoList.filter(i => i.mchntType === '1'), // 商圈信息
            upLineProduce: productInfoList.map(i => i.bizProdCode), // 纳入营销的交易
            onLineProduce: productInfoList.map(i => i.bizProdCode), // 纳入营销的交易 线下
            criteriaLimit: +mcInfoObj.criteriaLimit, // 有效交易定义
            statPeriod: mcInfoObj.statPeriod, // 统计周期
            criteriaAmount: +mcInfoObj.criteriaAmount, // 周期内收银员交易金额达标
            criteriaFlag: mcInfoObj.criteriaFlag, // 周期内收银员交易金额达标条件计算方式
            criteriaQuantity: +mcInfoObj.criteriaQuantity, // 周期内收银员交易笔数达标
            cashbackMethod: mcInfoObj.stockMchntType, // 营销方式交易类型
            ruleInfo: ruleInfoList, // 营销方式阶梯规则
            quantityLimitPerson: mcInfoObj.quantityLimitPerson, // 单个收银员统计交易笔数上限
            amountLimitPerson: mcInfoObj.amountLimitPerson, // 单个收银员统计交易金额上限
            cashbackLimitPerson: mcInfoObj.cashbackLimitPerson, // 单个收银员返现金额上限
            quantityLimitMc: mcInfoObj.quantityLimitMc, // 纳入返现总交易笔数上限
            amountLimitMc: mcInfoObj.amountLimitMc, // 纳入返现总交易金额上限
            cashbackLimitMc: mcInfoObj.cashbackLimitMc, // 返现总金额上限
            publishRefuseReason: mcInfoObj.publishRefuseReason, // 发布意见
            auditRefuseReason: mcInfoObj.auditRefuseReason, // 审核意见
            payAcctNo: mcInfoObj.payAcctNo, // 支付账号
            //优惠劵
            newMchntFlagView:newMchntFlagView,//活动期间新增商户
            afterFlagView:afterFlagView,//手续费优惠规则
            beforeFlagView:beforeFlagView,//达标前的交易通过返现营销
            postponeFlagView:postponeFlagView,//新增商户营销结束日期在营销活动结束日期之后
            stockMchnt:stockMchnt,//达标条件
            depositMonNum: mcInfoObj.depositMonNum,//月均存款平均月数
            statPeriod:mcInfoObj.statPeriod,//统计周期
            effectiveLimitTranNum:mcInfoObj.effectiveLimit,// 有效交易为：交易金额 ≥ 交易笔数
            effectiveLimitTranMoney:mcInfoObj.effectiveLimit,//有效交易为：交易金额 ≥交易笔数
            discoutPeriodTranNum:ruleInfoList[0].discountPeriod,//有效周期
            discoutPeriodTranMoney:ruleInfoList[0].discountPeriod,//有效周期
            discoutPeriodFeeMoney:ruleInfoList[0].discountPeriod,//有效周期
            newMchntPeriod:mcInfoObj.newMchntPeriod,//新增商户免手续费周期
            newMchntAmountLimit:mcInfoObj.newMchntAmountLimit,//每月优惠交易最大金额
            quantityLimit:quantityLimit,//单个存量商户优惠交易笔数上限
            amountLimit:amountLimit,//单个存量商户优惠交易金额上限
            feeLimit:feeLimit,//单个存量商户手续费优惠额上限
            flag:flag,//详细页面标识
            mcType:mcInfoObj.mcType//营销活动类型
            //end优惠劵
        }
    },
    async view (record) {
      const hideLoading = this.$message.loading('加载中...',0)
      try {
          const res = await this.$get('/admin/market/commissionManager/view?flag=rlaView&mcNo=' + record.mcNo)
        if (res.data.datailData) {
          this.$refs.CommissionMarketManagerOperation.show(this.resolveBeanInfo(res.data), 'view')
        }
      } catch (e) {
        console.error(e)
      }
      hideLoading()
    },
  },
  mounted() {
    this.search();
  }
}
</script>

<style scoped>
.page {
  width: 100%;
}
/deep/ .scrollable .ant-table td {
  white-space: nowrap;
}
</style>
